<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\Coupon;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Dcat\Admin\Widgets\Table;

class CouponController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new Coupon(), function (Grid $grid) {

            $grid->model()->with(['user','coupon_config']);
            $grid->model()->orderByDesc('id');

            $grid->column('id')->sortable();
            $grid->column('user.tiktokno', trans('user.fields.tiktokno'))->display(function ($var){
                return $this->user_id."({$var})";
            });
            $grid->column('coupon_config.title',trans('coupon-config.fields.title'));
            $grid->column('coupon_config.deduction_ratio',trans('coupon-config.fields.deduction_ratio'));
            $grid->column('coupon_config.quota',trans('coupon-config.fields.quota'))->display(function ($var) {
                return $var / 100;
            });
            $grid->column('used_quota')->display(function ($var) {
                return $var / 100;
            })->expand(function () {
                $logs = $this->coupon_log()->get()->map(function ($logs) {
                    return $logs->only(['id', 'order_total_amount', 'discount_amount', 'order_ids', 'created_at']);
                });
                $logs = $logs->toArray();
                foreach ($logs as &$log){
                    $log['order_total_amount'] = $log['order_total_amount'] /100;
                    $log['discount_amount'] = $log['discount_amount'] /100;
                }
                $data = $logs;
                return new Table(['ID', '订单总额', '抵扣金额', '订单ID', '抵扣时间'], $data);
            });
            $grid->column('receive_time');
            $grid->column('expiration_time');

            $grid->quickSearch('user.tiktokno','user.tiktokid','user_id');

            $grid->disableRowSelector();
            $grid->disableFilterButton();
            $grid->disableViewButton();
            $grid->showQuickEditButton();
            $grid->disableCreateButton();

        });
    }


    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new Coupon(), function (Form $form) {
            $form->display('id');

            $form->model()->used_quota = $form->model()->used_quota / 100;
            $form->text('used_quota')->required()->saving(function ($var) {
                $var = $var * 100;
                return $var;
            });
            $form->datetime('expiration_time')->required();
        });
    }
}
